package com.probox.common.entity.service.product.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.CategoryDepth;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.ProductAuditStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.product.ProductGroup;
import com.probox.common.entity.service.product.IProductGroupService;
import com.probox.common.redis.service.RedisService;
import com.probox.common.entity.domain.product.ProductInfo;
import com.probox.common.entity.domain.product.vo.OptionsSelect;
import com.probox.common.entity.domain.product.vo.ProductCategoryVo;
import com.probox.common.entity.service.product.IProductInfoService;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.product.ProductCategoryMapper;
import com.probox.common.entity.domain.product.ProductCategory;
import com.probox.common.entity.service.product.IProductCategoryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品类别Service业务层处理
 *
 * @date 2021-05-26
 */
@Service
@Transactional
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements IProductCategoryService {
    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IProductInfoService iProductInfoService;

    @Autowired
    private IProductGroupService productGroupService;

    /**
     * 查询商品类别
     *
     * @param categoryUid 商品类别ID
     * @return 商品类别
     */
    @Override
    public ProductCategory selectProductCategoryById(Long categoryUid) {
        return this.getById(categoryUid);
    }

    /**
     * 查询已经添加过的分类
     *
     * @return
     */
    @Override
    public HashMap getTestCategory() {
        HashMap map = new HashMap();
        QueryWrapper<ProductCategory> queryWrapper = Wrappers.query();
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.ne("PDD_CATEGORY_UID", 0);
        List<ProductCategory> list = productCategoryMapper.selectList(queryWrapper);
        if (ObjectUtil.isEmpty(list)) return map;
        list.forEach(cate -> map.put(cate.getPddCategoryUid(), cate.getCategoryUid()));
        return map;
    }

    /**
     * 查询商品类别列表
     *
     * @param productCategory 商品类别
     * @return 商品类别
     */
    @Override
    public List<ProductCategory> queryList(ProductCategory productCategory) {
        if (productCategory.getPlatformUid() == null) {
            Long platformId = SecurityUtils.getPlatformId();
            if (platformId == null) {
                throw new BaseException("当前账号异常");
            }
            productCategory.setPlatformUid(platformId);
        }
        QueryWrapper<ProductCategory> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getCategoryName())) && productCategory.getCategoryName() != null) {
            queryWrapper.like("CATEGORY_NAME", productCategory.getCategoryName());
        }

        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getDataStatus())) && productCategory.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", productCategory.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getCategoryDepth())) && productCategory.getCategoryDepth() != null) {
            queryWrapper.eq("CATEGORY_DEPTH", productCategory.getCategoryDepth());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getArrivalTime())) && productCategory.getArrivalTime() != null) {
            queryWrapper.eq("ARRIVAL_TIME", productCategory.getArrivalTime());
        }
        if (ObjectUtil.isNotEmpty(productCategory.getIsShow())) {
            queryWrapper.eq("IS_SHOW", productCategory.getIsShow());
        }
        if (productCategory.getGroupUid() != null){
            queryWrapper.eq("GROUP_UID", productCategory.getGroupUid());
        }
        queryWrapper.eq("PLATFORM_UID", productCategory.getPlatformUid());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getDataPriority())) && productCategory.getDataPriority() != null) {
            queryWrapper.orderByAsc("DATA_PRIORITY");
        } else {
            queryWrapper.orderByAsc("DATA_PRIORITY");
            queryWrapper.orderByDesc("UPDATE_TIME");
        }
        List<ProductCategory> list = productCategoryMapper.selectList(queryWrapper);
        for (ProductCategory cate:list) {
            if (cate.getGroupUid() != null){
                ProductGroup pg = productGroupService.getById(cate.getGroupUid());
                if (pg != null){
                    cate.setGroupName(pg.getGroupName());
                }
            }
        }
        return list;
    }

    @Override
    public Integer selectCategoryCount(ProductCategory productCategory) {
        if (productCategory.getPlatformUid() == null) {
            Long platformId = SecurityUtils.getPlatformId();
            if (platformId == null) {
                throw new BaseException("当前账号异常");
            }
            productCategory.setPlatformUid(platformId);
        }
        QueryWrapper<ProductCategory> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getCategoryName())) && productCategory.getCategoryName() != null) {
            queryWrapper.like("CATEGORY_NAME", productCategory.getCategoryName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getDataStatus())) && productCategory.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", productCategory.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getCategoryDepth())) && productCategory.getCategoryDepth() != null) {
            queryWrapper.eq("CATEGORY_DEPTH", productCategory.getCategoryDepth());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productCategory.getArrivalTime())) && productCategory.getArrivalTime() != null) {
            queryWrapper.eq("ARRIVAL_TIME", productCategory.getArrivalTime());
        }
        queryWrapper.eq("PLATFORM_UID", productCategory.getPlatformUid());
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.orderByAsc("DATA_PRIORITY");
        return productCategoryMapper.selectList(queryWrapper).size();
    }

    /**
     * 新增商品类别 pdd测试
     *
     * @param productCategory 商品类别
     * @return 结果
     */
    @Override
    public ProductCategory insertProductCategoryPdd(ProductCategory productCategory) {
        //先查询是否存在
        QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("PDD_CATEGORY_UID", productCategory.getPddCategoryUid());
        queryWrapper.eq("PLATFORM_UID", productCategory.getPlatformUid());
        ProductCategory category = productCategoryMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(category)) return category;
        // 分类名称不为重名
        Integer result = queryCategoryName(productCategory);
        if (result > 0) {
            throw new ProductException("专业名称不能重名！");
        }
        if (CategoryDepth.one.getKey().equals(productCategory.getCategoryDepth())) {
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TOP + SecurityUtils.getPlatformId());
        }
        this.save(productCategory);
        return productCategory;
    }


    /**
     * 新增商品类别
     *
     * @param productCategory 商品类别
     * @return 结果
     */
    @Override
    public boolean insertProductCategory(ProductCategory productCategory) {
        // 分类名称不为重名
        Integer result = queryCategoryName(productCategory);
        if (result > 0) {
            throw new ProductException("专业名称不能重名！");
        }
        productCategory.setPlatformUid(SecurityUtils.getPlatformId());
        productCategory.setUpdateUid(SecurityUtils.getUserId());
        productCategory.setUpdateName(SecurityUtils.getUsername());
        productCategory.setUpdateTime(DateUtil.date());
        if (productCategory.getGroupUid() == null && productCategory.getCategoryDepth()==1 && productCategory.getCategoryPuid() != null){
            productCategory.setGroupUid(this.selectProductCategoryById(productCategory.getCategoryPuid()).getGroupUid());
        }
        //productCategory.setDataStatus(DataStatus.invalid.getKey());
        /*if (DataStatus.valid.getKey().equals(productCategory.getDataStatus())) {
            if (CategoryDepth.two.getKey().equals(productCategory.getCategoryDepth()))
                redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + productCategory.getCategoryPuid());
        }
        if (CategoryDepth.one.getKey().equals(productCategory.getCategoryDepth())) {
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TOP + SecurityUtils.getPlatformId());
        }*/
        // redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_CASCADER + SecurityUtils.getPlatformId());
        return this.save(productCategory);
    }

    /**
     * 修改商品类别
     *
     * @param productCategory 商品类别
     * @return 结果
     */
    @Override
    public boolean updateProductCategory(ProductCategory productCategory) {
        // 分类名称不为重名
        Integer result = queryCategoryName(productCategory);
        if (result > 0) {
           // throw new ProductException("专业名称不能重名！");
        }
        /*
        if (DataStatus.invalid.getKey().equals(productCategory.getDataStatus())) {
            ProductInfo info = new ProductInfo();
            if (CategoryDepth.one.getKey().equals(productCategory.getCategoryDepth()))
                info.setCategoryUidOne(productCategory.getCategoryUid());
            if (CategoryDepth.two.getKey().equals(productCategory.getCategoryDepth()))
                info.setCategoryUidTwo(productCategory.getCategoryUid());
            if (CategoryDepth.three.getKey().equals(productCategory.getCategoryDepth()))
                info.setCategoryUidThree(productCategory.getCategoryUid());
            if (iProductInfoService.useProduct(info)) throw new ProductException("该商品分类已被使用,无法无效！");
        }*/
        productCategory.setUpdateUid(SecurityUtils.getUserId());
        productCategory.setUpdateName(SecurityUtils.getUsername());
        productCategory.setUpdateTime(DateUtil.date());
        if (productCategory.getGroupUid() == null && productCategory.getCategoryDepth()==1 && productCategory.getCategoryPuid() != null){
            productCategory.setGroupUid(this.selectProductCategoryById(productCategory.getCategoryPuid()).getGroupUid());
        }
       /* if (CategoryDepth.one.getKey().equals(productCategory.getCategoryDepth())) {
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TOP + SecurityUtils.getPlatformId());
        }
        if (CategoryDepth.two.getKey().equals(productCategory.getCategoryDepth()))
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + productCategory.getCategoryPuid());*/
        return this.updateById(productCategory);
    }

    /**
     * 批量删除商品类别
     *
     * @param categoryUids 需要删除的商品类别ID
     * @return 结果
     */
    @Override
    public boolean deleteProductCategoryByIds(Long[] categoryUids) {
        UpdateWrapper<ProductCategory> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("CATEGORY_UID", Arrays.asList(categoryUids));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    /**
     * 修改商品类别状态
     *
     * @param productCategory 商品类别
     * @return 结果
     */
    @Override
    public boolean updateCategoryStatus(ProductCategory productCategory) {
        if (CategoryDepth.one.getKey().equals(productCategory.getCategoryDepth())) {
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TOP + SecurityUtils.getPlatformId());
        }
        if (CategoryDepth.two.getKey().equals(productCategory.getCategoryDepth()))
            redisService.deleteObject(CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + productCategory.getCategoryPuid());
        return this.updateProductCategory(productCategory);
    }

    /**
     * api 获取分类下的子级分类,还有相关的商品图片
     *
     * @param categoryUid
     * @return
     */
    @Override
    public ProductCategoryVo getCategoryVo(Long categoryUid) {
        String key = CachePrefix.PRODUCT_CATEGORY_TWO_BANNER + categoryUid;
        ProductCategoryVo productCategoryVo = redisService.get(key, ProductCategoryVo.class);
        if (ObjectUtil.isEmpty(productCategoryVo)) {
            productCategoryVo = new ProductCategoryVo();
            productCategoryVo.setBannerShops(iProductInfoService.getGategoryProduct(categoryUid));
            QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            queryWrapper.eq("CATEGORY_DEPTH", CategoryDepth.two.getKey());
            queryWrapper.eq("CATEGORY_PUID", categoryUid);
            queryWrapper.eq("IS_SHOW", "1");
            queryWrapper.orderByAsc("DATA_PRIORITY");
            productCategoryVo.setProductCategory(productCategoryMapper.selectList(queryWrapper));
            redisService.set(key, productCategoryVo, 15L, TimeUnit.DAYS);
        }
        return productCategoryVo;
    }

    /**
     * 查询该等级的类别
     *
     * @param depth 等级
     * @return
     */
    @Override
    public List<ProductCategory> getCategoryDepthList(String depth, Long uid) {
        QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CATEGORY_DEPTH", depth);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("PLATFORM_UID", uid);
        return productCategoryMapper.selectList(queryWrapper);
    }

    @Override
    public List<ProductCategory> getCategoryOne(String depth, Long uid) {
        String key = CachePrefix.PRODUCT_CATEGORY_TOP + uid;
        List<ProductCategory> cacheList = redisService.getCacheList(key);
        if (ObjectUtil.isEmpty(cacheList)) {
            QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CATEGORY_DEPTH", depth);
            queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
            queryWrapper.eq("PLATFORM_UID", uid);
            queryWrapper.eq("IS_SHOW", "1");
            queryWrapper.orderByAsc("DATA_PRIORITY");
            cacheList = productCategoryMapper.selectList(queryWrapper);
            redisService.setCacheList(key, cacheList);
            redisService.expire(key,1L,TimeUnit.DAYS);
        }
        return cacheList;

    }

    /**
     * 查询类别重名
     *
     * @param category
     * @return
     */
    @Override
    public Integer queryCategoryName(ProductCategory category) {
        /*
        QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CATEGORY_NAME", category.getCategoryName());
        //
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.eq("CATEGORY_DEPTH", category.getCategoryDepth());
        if (ObjectUtil.isNotEmpty(category.getGroupUid())) {
            queryWrapper.ne("GROUP_UID", category.getGroupUid());
        }
        return productCategoryMapper.selectCount(queryWrapper);

         */
        return 0;
    }

    /**
     * 获取分类的级联
     *
     * @return
     */
    @Override
    public List<OptionsSelect> selectOptionList() {
        List<OptionsSelect> collect = null;
        ProductCategory productCategory = new ProductCategory();
        productCategory.setDataStatus(DataStatus.valid.getKey());
        productCategory.setDataPriority(1L);
        List<ProductCategory> list = this.queryList(productCategory);
        List<ProductCategory> returnList = new ArrayList<ProductCategory>();
        List<Long> tempList = new ArrayList<Long>();
        for (ProductCategory category : list) {
            tempList.add(category.getCategoryUid());
        }
        for (Iterator<ProductCategory> iterator = list.iterator(); iterator.hasNext(); ) {
            ProductCategory category = (ProductCategory) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(category.getCategoryPuid())) {
                recursionFn(list, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty()) {
            returnList = list;
        }
        collect = returnList.stream().map(OptionsSelect::new).collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取商品分类的名称
     *
     * @param productInfo 商品信息
     * @return
     */
    @Override
    public String getCategoryName(ProductInfo productInfo) {
        StringBuffer name = new StringBuffer("");
        Long[] uids = new Long[3];
        uids[0] = productInfo.getMajorUidOne();
        uids[1] = productInfo.getMajorUidTwo();
        uids[2] = productInfo.getMajorUidThree();
        QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("CATEGORY_UID", uids);
        List<ProductCategory> list = productCategoryMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(list))
            list.stream().forEach(productCategory -> name.append("> " + productCategory.getCategoryName()));
        String s = name.toString();
        if (StringUtils.isNotEmpty(s)) return s.substring(1, s.length());
        return null;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<ProductCategory> list, ProductCategory t) {
        // 得到子节点列表
        List<ProductCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ProductCategory tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ProductCategory> getChildList(List<ProductCategory> list, ProductCategory t) {
        List<ProductCategory> tlist = new ArrayList<ProductCategory>();
        Iterator<ProductCategory> it = list.iterator();
        while (it.hasNext()) {
            ProductCategory n = (ProductCategory) it.next();
            if (n.getCategoryPuid().longValue() == t.getCategoryUid().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    private boolean hasChild(List<ProductCategory> list, ProductCategory t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }


}
